# coding: utf-8
# -*- mode: xonsh; -*-

import os
import shlex
from shutil import which

source-foreign zsh --login True --overwrite-alias "echo loading xonsh foreign shell"

xontrib load readable-traceback

if ${...}.get('INSIDE_EMACS', False):
    $TITLE = None
else:
    $TITLE = '{current_job:{} | }{user}@{hostname}: {short_cwd} | xonsh'

if $TERM == "dumb":
    $PS1="> "

$HOME = os.path.expanduser('~')
$PATH.insert(0, $HOME + '/.bin')
$PATH.insert(0, $HOME + '/.local/bin')
$SHELL_TYPE = 'prompt_toolkit'

if os.path.exists(f'{$HOME}/.pyenv'):
    $PYENV_ROOT = f'{$HOME}/.pyenv'
    $PATH.insert(0, $PYENV_ROOT + '/bin')
    source-foreign zsh --overwrite-alias $(pyenv init -)
    source-foreign zsh --overwrite-alias $(pyenv virtualenv-init -)
    $BASH_COMPLETIONS.insert(0, $PYENV_ROOT + '/completions')

if os.path.exists(f'{$HOME}/.emacs.d/bin'):
    $PATH.insert(0, $HOME + '/.emacs.d/bin')

# Enable AUTO_CD
$AUTO_CD = True

# Default
$BROWSER = "firefox"
$TERM = "screen-256color"
$EDITOR = '/usr/bin/emacs'

# $GDK_SCALE = 2
# $GDK_DPI_SCALE = 0.5

# Encoding
$LANG = "es_EC.UTF-8"
$LC_ALL = "es_EC.UTF-8"

# keep the prompt short
$DYNAMIC_CWD_WIDTH = '20%'

# ptk display stuff
$CASE_SENSITIVE_COMPLETIONS = False
$COMPLETIONS_BRACKETS = True
$COMPLETIONS_CONFIRM = True

# Less Stuff
$PAGER = 'eless'
$LESS = '-iMSx4 -FX'

# Ignore Errors
$XONSH_ENCODING_ERRORS = 'ignore'

$XONSH_GITSTATUS_HASH = "{NO_COLOR}:"
$XONSH_GITSTATUS_BRANCH = "{BOLD_PURPLE}"
$XONSH_GITSTATUS_OPERATION = "{CYAN}"
$XONSH_GITSTATUS_STAGED = "{RED}●"
$XONSH_GITSTATUS_CONFLICTS = "{RED}×"
$XONSH_GITSTATUS_CHANGED = "{BOLD_BLUE}+"
$XONSH_GITSTATUS_UNTRACKED = "{NO_COLOR}…"
$XONSH_GITSTATUS_CLEAN = "{BOLD_GREEN}✔"
$XONSH_GITSTATUS_AHEAD = "{NO_COLOR}↑"
$XONSH_GITSTATUS_BEHIND = "{NO_COLOR}↓"
$SUPPRESS_BRANCH_TIMEOUT_MESSAGE = True

def pyenv_prompt():
    pyenv_name = ""
    if $(pyenv version-name).replace('\n', '') != 'system':
        pyenv_name = $(pyenv version-name).replace('\n', '')
    return pyenv_name

$PROMPT_FIELDS['pyenv_prompt'] = pyenv_prompt

$PROMPT = "{BOLD_WHITE}{pyenv_prompt}{NO_COLOR}{BOLD_BLUE} »{NO_COLOR} "
$RIGHT_PROMPT = "{gitstatus: {}} {BOLD_INTENSE_BLACK}{short_cwd}{NO_COLOR} "

# Aliases (yeah... no shit, kid)
def _pyclean():
    from os.path import Path
    d = Path($PWD)
    bflist = ["c", "o"]
    for b in bflist:
        files = d.walkfiles("*.py{}".format(b))
        for f in files:
            f.remove_p()
    for dir in d.walkdirs("__pycache__"):
        dir.removedirs_p()
    return True


def _get_branch_name():
    import os
    from subprocess import call, STDOUT, check_output
    branch = ""
    if not call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) != 0:
        out = check_output(["git", "branch"]).decode("utf8")
        current = next(line for line in out.split("\n") if line.startswith("*"))
        branch = current.strip("*").strip()
    return branch, call

def _git_pull_current_branch():
    branch, call = _get_branch_name()
    if branch:
        call(["git", "pull", "origin", branch])

def _git_push_current_branch():
    branch, call = _get_branch_name()
    if branch:
        call(["git", "push", "origin", branch])


custom = {}

pairs = (
    ("dt", "dotdrop -c ~/.dotdrop.yml"),
    ("ls", "exa"),
    ("mkdir", "mkdir -p"),
    ("lookup", '/usr/bin/dict'),
    ("next", '/usr/bin/next'),
    ("ping", 'ping -4'),
    ("rm", "safe-rm"),
    ('cp', 'acp -g'),
    ('mv', 'amv -g'),
    ('pyc', _pyclean),
    ('pyi', 'python setup.py install'),
    ('pyd', 'python setup.py develop'),
    ('pyb', 'python setup.py build'),
    ('ggpull', _git_pull_current_branch),
    ('ggpush', _git_push_current_branch),
    ('ggpt', 'git pull --tags'),
    ('dco', 'docker-compose'),
    ('dcb', 'docker-compose build'),
    ('dce', 'docker-compose exec'),
    ('dcps', 'docker-compose ps'),
    ('dcrestart', 'docker-compose restart'),
    ('dcrm', 'docker-compose rm'),
    ('dcr', 'docker-compose run'),
    ('dcstop', 'docker-compose stop'),
    ('dcup', 'docker-compose up'),
    ('dcupd', 'docker-compose up -d'),
    ('dcdn', 'docker-compose down'),
    ('dcl', 'docker-compose logs'),
    ('dclf', 'docker-compose logs -f'),
    ('dcpull', 'docker-compose pull'),
    ('dcstart', 'docker-compose start'),

)

for pair in pairs:
    key, name = pair
    if callable(name):
        name.__xonsh__threadable = False
        name.__xonsh__capturable = False

    if callable(name) or which(shlex.split(name)[0]) is not None:
        custom[key] = name

aliases.update(custom)

del os
del shlex
